﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace ItemsViewerDemo
{
    /// <summary>
    /// Waiting control.
    /// </summary>
    public partial class CircularLoader : UserControl
    {
        /// <summary>
        /// Gets or sets a value indicating this loader is busy.
        /// </summary>
        public static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register("IsBusy", typeof(bool), typeof(CircularLoader), new PropertyMetadata(IsBusyChanged));

        /// <summary>
        ///  Initializes a new instance of the CircularLoader class.
        /// </summary>
        public CircularLoader()
        {
            InitializeComponent();
            this.Visibility = System.Windows.Visibility.Collapsed;
        }

        /// <summary>
        /// Gets or sets a value indicating whether loader is busy.
        /// </summary>
        public bool IsBusy
        {
            get { return (bool)GetValue(IsBusyProperty); }
            set { SetValue(IsBusyProperty, value); }
        }

        /// <summary>
        /// Start Animation.
        /// </summary>
        public void StartAnimation()
        {
            this.Visibility = System.Windows.Visibility.Visible;
            (this.Resources["LoaderAnimation"] as Storyboard).Begin();
        }

        /// <summary>
        /// Start Animation.
        /// </summary>
        public void StopAnimation()
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            (this.Resources["LoaderAnimation"] as Storyboard).Stop();
        }

        /// <summary>
        /// IsBusy value Changed.
        /// </summary>
        /// <param name="d">The DependencyObject.</param>
        /// <param name="e">The DependencyPropertyChangedEventArgs.</param>
        private static void IsBusyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CircularLoader dlg = d as CircularLoader;
            if (dlg == null)
            {
                return;
            }

            if (dlg.IsBusy)
            {
                dlg.StartAnimation();
            }
            else
            {
                dlg.StopAnimation();
            }
        }
    }
}
